package ruc.DolphinDB.compress;

import com.xxdb.DBConnection;
import com.xxdb.data.*;
import ruc.Consts.constant;
import ruc.DolphinDB.DolphinDB_Common;
import ruc.utils.IOUtils;

import java.io.IOException;
import java.util.HashMap;

class Info {
    float cpu_usage, memory_usage, disk_usage;
    public Info(float cpu_usage, float memory_usage, float disk_usage){
        this.cpu_usage = cpu_usage;
        this.memory_usage = memory_usage;
        this.disk_usage = disk_usage;
    }
}

public class DolphinDB_Accuracy {
    private int bound, port;
    private String IP, tbName;

    public DolphinDB_Accuracy(String IP, int port, String tbName,int bound) {
        this.IP = IP;
        this.port = port;
        this.tbName = tbName;
        this.bound = bound;
    }

    private HashMap convert(String[] list) throws IOException {
        HashMap<String, Info> map = new HashMap();
        for(int k = 0; k < list.length; k++) {
            String[] v = list[k].split(constant.Delimiter);
            Info info = new Info(Float.parseFloat(v[4]), Float.parseFloat(v[5]), Float.parseFloat(v[6]));
            map.put(Long.parseLong(v[0]) + v[1] + v[2] + v[3], info);
        }
        return map;
    }

    private float loopBasicType(BasicTable table, HashMap<String, Info> map) {
        float res = 0;
        // 取出每一列的内容
        BasicTimestampVector ts = (BasicTimestampVector) table.getColumn("timestamp");
        BasicFloatVector userInfo = (BasicFloatVector) table.getColumn("userInfo");
        BasicFloatVector hostname = (BasicFloatVector) table.getColumn("hostname");
        BasicFloatVector server = (BasicFloatVector) table.getColumn("server");
        BasicFloatVector cpuUsage = (BasicFloatVector)table.getColumn("cpu_usage");
        BasicFloatVector memoryUsage = (BasicFloatVector)table.getColumn("memory_usage");
        BasicFloatVector diskUsage = (BasicFloatVector)table.getColumn("disk_usage");
        for(int i = 0; i < table.rows(); i++) {
            String key = ts.getTimestamp(i).toString() + userInfo.get(i).toString() +
                    hostname.get(i).toString() + server.get(i).toString();
            Info info = map.get(key);
            res += Math.pow(info.cpu_usage - cpuUsage.getFloat(i), 2);
            res += Math.pow(info.disk_usage - diskUsage.getFloat(i), 2);
            res += Math.pow(info.memory_usage - memoryUsage.getFloat(i), 2);
        }

        return res / table.rows();
    }

    private float calAccuracy() throws IOException {
        DBConnection con = DolphinDB_Common.getDBConnection(IP, port);
        BasicTable table = (BasicTable)con.run(String.format("select * from %s", tbName));
        HashMap map = convert(IOUtils.GetData());
        return loopBasicType(table, map);
    }
}
